package xyz.xiangyushui.controller.admin.store;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import xyz.xiangyushui.dao.admin.StoreDao;

/**
 * Servlet implementation class StoreCreate
 */
@WebServlet("/admin/storeValidater")
public class StoreValidater extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private StoreDao sd;
	private final String emptyWarning = "Incomplete form!";
	private final String storeExist = "The store already exists!";
	private final String successMsg = "store successfully created!";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public StoreValidater() {
		super();
		sd = new StoreDao();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String storeName = request.getParameter("storeName");
		String comment = request.getParameter("comment");
		String msg = validate(storeName);
		
		if (msg.equals(successMsg)) {
			sd.addStore(storeName, comment);
			request.setAttribute("successMsg", msg);
		}else{
			request.setAttribute("failedMsg", msg);
		}
		request.getRequestDispatcher("/admin/store/create").forward(request, response);
	}

	private String validate(String storeName) {
		String result = successMsg;
		if ("".equals(storeName)) {
			result = emptyWarning;
		} else {
			if (sd.exists(storeName)) {
				result = storeExist;
			}
		}
		return result;
	}

}
